import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { renderAndSendMsgAuto } from '../resources/xr/xr.js'; // 假设之前优化后的渲染模块路径

// 获取当前文件路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 数据存储目录及文件
const HELP_DIR = path.resolve(__dirname, '../data/help');
const HELP_FILE = path.join(HELP_DIR, 'help.json');
const BG_IMAGES_DIR = path.resolve(__dirname, '../data/背景图');
const BG_IMAGES_FILE = path.join(BG_IMAGES_DIR, 'square_images.json');

// 确保数据目录存在
function ensureDirectoryExists(dir) {
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true });
    }
}

ensureDirectoryExists(HELP_DIR);
ensureDirectoryExists(BG_IMAGES_DIR);

// 确保数据文件存在
function ensureFileExists(file, initialContent = '{}') {
    if (!fs.existsSync(file)) {
        fs.writeFileSync(file, initialContent);
    }
}

ensureFileExists(HELP_FILE);
ensureFileExists(BG_IMAGES_FILE, '[]');

class PippiHelpPlugin extends plugin {
    constructor() {
        super({
            name: 'pippi_help',
            dsc: '皮皮帮助插件',
            event: 'message',
            priority: 500,
            rule: [
                { reg: "^皮皮帮助 (.+)$", fnc: 'displayHelp', permission: 'all' }
            ],
        });
    }

    // 显示帮助信息
    async displayHelp(e) {
        const helpKey = e.msg.replace(/^皮皮帮助 /, '').trim();
        const helpData = this.loadHelpData();

        if (!helpData[helpKey]) {
            return e.reply(`没有找到 '${helpKey}' 的帮助信息。`, true, { recallMsg: 10 });
        }

        // 获取帮助内容并按行分割
        const helpMessage = helpData[helpKey];
        const formattedHelpMessage = this.formatHelpMessage(helpMessage);

        const statsMessage = `皮皮帮助 - ${helpKey}\n═════════════════════════\n` + formattedHelpMessage;

        const imageUrl = this.getRandomBackgroundImage();
        try {
            await renderAndSendMsgAuto(e, imageUrl, statsMessage, `皮皮帮助 - ${helpKey}`);
        } catch (error) {
            console.error('渲染帮助信息时出错:', error);
            e.reply('渲染帮助信息时出现错误，请稍后再试。');
        }
    }

    // 将帮助信息按行分割并格式化
    formatHelpMessage(helpMessage) {
        return helpMessage
           .split('\n')  // 按行分割
           .map(line => `  ${line.trim()}`)  // 去除多余空格并加上缩进
           .join('\n');  // 将所有行重新拼接成字符串
    }

    // 获取随机背景图片
    getRandomBackgroundImage() {
        const backgroundImages = this.loadBackgroundImages();
        if (backgroundImages.length === 0) {
            return 'https://krseoul.imgtbl.com/i/2024/07/21/669d24f593308.jpeg';
        }
        const randomIndex = Math.floor(Math.random() * backgroundImages.length);
        return backgroundImages[randomIndex];
    }

    // 加载帮助数据
    loadHelpData() {
        try {
            const data = fs.readFileSync(HELP_FILE, 'utf-8');
            return JSON.parse(data);
        } catch (error) {
            console.error('加载帮助数据失败:', error);
            return {};
        }
    }

    // 加载背景图链接
    loadBackgroundImages() {
        try {
            const data = fs.readFileSync(BG_IMAGES_FILE, 'utf-8');
            return JSON.parse(data);
        } catch (error) {
            console.error('加载背景图链接失败:', error);
            return [];
        }
    }
}

export default PippiHelpPlugin;